import { IconFont } from '@nutui/icons-react-taro'
import { Button, Tabs } from '@nutui/nutui-react-taro'
import { ScrollView, Text, View } from '@tarojs/components'
import { useCallback, useMemo, useState } from 'react'
import { useRequest } from 'taro-hooks'
import Card from '../../components/card'
import FeeDetails from '../../components/fee-details'
import ImageGallery, { ImageItem } from '../../components/image-gallery'
import Layout from '../../components/layout'
import { QuotationCategory, THEME_COLORS } from '../../constants/index'
import { useNavigation } from '../../hooks'
import { Category, PackageDescription, ProductPackage, SubCategory } from '../../inteface/product-info'
import { calculatePrice, getProductInfo } from '../../services/product'
import './index.less'

const ProjectDetails: React.FC = () => {
  const { params, goHome, navigateTo } = useNavigation()
  const projectId = params.id as string
  const [tabValue, setTabValue] = useState<string | number>('0')
  const {
    runAsync: calculatePriceRun,
    data: calculatePriceData,
    loading: calculatePriceLoading,
  } = useRequest(calculatePrice, {
    manual: true,
    defaultParams: [{ productId: Number(projectId) }],
  })
  const { data, loading } = useRequest(getProductInfo, {
    defaultParams: [{ productId: projectId }],
  })

  const packageImages: ImageItem[] = useMemo(
    () =>
      data?.product?.images.map((img) => ({
        src: img,
      })) || [],
    [data?.product?.images],
  )

  // 项目费用明细数据
  const projectFeeCategories: QuotationCategory[] = useMemo(() => {
    return calculatePriceData?.data?.categories.map((category) => {
      return {
        category: category.categoryName,
        total: category.totalPrice,
      }
    })
  }, [calculatePriceData])

  const packageContent = useCallback((packageItem: ProductPackage) => {
    try {
      const description = JSON.parse(packageItem.description) as PackageDescription
      const categories = description.categories
      const _categories = categories.map((category: Category) => {
        return {
          icon: <IconFont fontClassName='iconfont' classPrefix='icon' name='kuaijiezhifu' size={20} />,
          categoryName: category.name,
          subCategories: category.subCategories.map((subCategory: SubCategory) => {
            return { description: subCategory.description }
          }),
        }
      })
      return { _categories, name: packageItem.name, id: packageItem.id }
    } catch (error) {
      console.log(error)
    }
  }, [])

  return (
    <Layout
      title={data?.product?.name}
      showTabBar={false}
      loading={loading}
      footer={
        <View className='footer-buttons'>
          <Button
            type='primary'
            size='large'
            className='appointment-button'
            onClick={() => {
              navigateTo('/pages/quick-appointment/index?packageId=' + tabValue)
            }}>
            一键预约
          </Button>
          <Button
            type='default'
            size='large'
            className='quote-button'
            onClick={() => {
              navigateTo('/pages/fee-estimation/index?packageId=' + tabValue)
            }}>
            透明报价
          </Button>
        </View>
      }>
      {/* Main Content */}
      <ScrollView className='project-details-content' scrollY>
        {/* 图片展示区域 */}
        <ImageGallery images={packageImages} height={300} className='project-image-gallery' />

        {/* 项目标题和描述 */}
        <View className='project-info p-16'>
          <Text className='project-title'>{data?.product?.name}</Text>
          <Text className='project-description'>{data?.product?.description}</Text>
        </View>

        {/* 套餐选择 */}
        <View className='package-selection mt-16'>
          <Text className='section-title p-16'>套餐选择</Text>
          <Tabs
            value={tabValue}
            activeType='button'
            onChange={(value) => {
              setTabValue(value)
              calculatePriceRun({ packageId: Number(value), productId: Number(projectId) })
            }}>
            {data?.product?.availablePackages.map((_package) => (
              <Tabs.TabPane key={_package?.id} title={_package?.name} value={_package?.id}>
                {/* 详细信息 */}
                <View className='details-section'>
                  {packageContent(_package)?._categories?.map((section, index) => (
                    <Card key={index} padding='none' className='detail-card'>
                      <View className='detail-header'>
                        <View className='detail-icon' style={{ backgroundColor: `${THEME_COLORS.primary}20` }}>
                          <Text className='icon-text' style={{ color: THEME_COLORS.primary }}>
                            {section.icon}
                          </Text>
                        </View>
                        <Text className='detail-title'>{section.categoryName}</Text>
                      </View>

                      {section.subCategories && (
                        <View className='detail-list'>
                          {section.subCategories.map((item, itemIndex) => (
                            <View key={itemIndex} className='list-item'>
                              <Text className='list-dot'>•</Text>
                              <Text className='list-text'>{item.description}</Text>
                            </View>
                          ))}
                        </View>
                      )}
                    </Card>
                  ))}
                  {/* 费用明细 */}
                  <Card padding='md' className='detail-card'>
                    <View className='detail-header'>
                      <View className='detail-icon' style={{ backgroundColor: `${THEME_COLORS.primary}20` }}>
                        <Text className='icon-text' style={{ color: THEME_COLORS.primary }}>
                          <IconFont fontClassName='iconfont' classPrefix='icon' name='zhifudingjin' size={20} />
                        </Text>
                      </View>
                      <Text className='detail-title'>项目费用明细</Text>
                    </View>
                    <View className='detail-description'>
                      <FeeDetails
                        showTitle={false}
                        showCard={false}
                        loading={calculatePriceLoading}
                        categories={projectFeeCategories}
                        totalAmount={calculatePriceData?.data?.totalPrice}
                        title='项目费用明细'
                        primaryColor={THEME_COLORS.primary}
                        note='*此报价为估算价格，最终价格以实际测量和材料选择为准。'
                      />
                    </View>
                  </Card>
                </View>
              </Tabs.TabPane>
            ))}
          </Tabs>
        </View>
      </ScrollView>
    </Layout>
  )
}

export default ProjectDetails
